//
//  HJInformationBlockchainController.m
//  KaiChat
//
//  Created by lx on 2024/3/11.
//

#import "HJBlockchainInformationController.h"
#import "HJInformationBlockchainCell.h"
#import "HJInformationTabView.h"
#import "HJInformationModel.h"
#import "HJInformationTabController.h"
#import "HJInformationPresent.h"
#import "HJNewsTabModel.h"
#import "HJNewsTabListModel.h"
#import "HJRefreshHeader.h"
#import "HJRefreshFooter.h"
#import "HJFlutterController.h"
#import "HJUserNewsTagModel.h"
#import "TJEmptyDataHandler.h"
#import "HJShareController.h"

@interface HJBlockchainInformationController ()<HJInformationTabControlViewDelegate, HJInformationCellDelegate>

@property (nonatomic, strong) NSMutableArray *datas;
@property (nonatomic, strong) HJInformationTabView *header;
@property (nonatomic, assign) NSInteger pageIndex;
@property (nonatomic, strong) NSMutableArray<HJNewsTabModel *> *tempTabDatas;
@property (nonatomic, copy) NSString *selectTagId;
@property (nonatomic, strong) TJEmptyDataHandler *emptyDataHandler;

@end

@implementation HJBlockchainInformationController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.pageIndex = 1;
    
    [self.view addSubview:self.header];
    
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 0.1)];
    [self.tableView registerClass:HJInformationBlockchainCell.class forCellReuseIdentifier:@"HJInformationBlockchainCell"];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.tableView.mj_header = [HJRefreshHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    self.tableView.mj_footer = [HJRefreshFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    self.tableView.mj_footer.hidden = YES;
    self.tableView.mj_header.hidden = YES;

    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(_header.frame.size.height);
        make.left.right.bottom.offset(0);
    }];
    
    _emptyDataHandler = [TJEmptyDataHandler emptyDataHandleWithScrollView:self.tableView];
    
}

- (void)loadData {
    if (_datas.count == 0) {
        dispatch_async_sql_queue(^{
            HJUserNewsTagModel *userTagModel = [HJUserNewsTagModel bg_find:[HJUserNewsTagModel bg_tableName] where:[NSString stringWithFormat:@"where %@=%@", bg_sqlKey(@"key"), bg_sqlValue([HJUserNewsTagModel getKeyWithUserId:HJUserInfo.userId typeId:toString(@(self.newsTypeId))])]].firstObject;
            if ([userTagModel.selectTag intValue]) {
                self.selectTagId = userTagModel.selectTag;
            } else {
                self.selectTagId = @"-1";
            }
            dispatch_async_main_queue(^{
                [self showLoading];
                [self loadNewData];
            });
        });
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.datas.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HJInformationBlockchainCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HJInformationBlockchainCell" forIndexPath:indexPath];
    HJBlockchainInformationLayout *model = self.datas[indexPath.row];
    cell.layout = model;
    cell.delegate = self;
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    HJBlockchainInformationLayout *layout = self.datas[indexPath.row]; 
    HJFlutterController *flutterController = [[HJFlutterController alloc] initWithName:HJFlutterPageNews];
    flutterController.arguments = @{
        @"type": @(self.type),
        @"id": layout.model.informationId
    };
    [self.navigationController pushViewController:flutterController];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    HJBlockchainInformationLayout *model = self.datas[indexPath.row];
    return model.height;
}

- (HJInformationTabView *)header {
    if (!_header) {
        _header = [[HJInformationTabView alloc]initWithFrame:CGRectMake(0, 0, KScreenWidth, 50)];
        _header.delegate = self;
    }
    return _header;
}

- (NSMutableArray *)datas {
    if (!_datas) {
        _datas = [NSMutableArray array];
    }
    return _datas;
}


#pragma mark - HJInformationTabControlViewDelegate
- (void)view:(HJInformationTabView *)view didSelectItem:(HJNewsTabModel *)model {
    NSLog(@"选中了%@", model);
    [self selectTagModel:model];
}

- (void)didClickMore:(HJInformationTabView *)view {
    TJWeakify(self)
    HJInformationTabController *informationTabController = [[HJInformationTabController alloc] init];
    informationTabController.typeId = self.newsTypeId;
    [informationTabController setLikeTagDidChangeBlock:^(NSMutableArray<HJNewsTabModel *> * _Nonnull likeTabs, BOOL isAdd, HJNewsTabModel * _Nonnull model) {
        if (!weakself.header.datas) {
            weakself.header.datas = [NSMutableArray array];
        }
        if (isAdd) {
            
            HJNewsTabModel *addModel = nil;
            for (HJNewsTabModel *obj in weakself.header.datas) {
                if (model.tagID == obj.tagID) {
                    addModel = obj;
                    break;
                }
            }
            
            if (!addModel) {
                [weakself.header.datas addObject:model];
            }
        } else {
            
            HJNewsTabModel *removeModel = nil;
            for (HJNewsTabModel *obj in weakself.header.datas) {
                if (model.tagID == obj.tagID) {
                    removeModel = obj;
                    break;
                }
            }
            
            if (removeModel) {
                [weakself.header.datas removeObject:removeModel];
                if (removeModel.isSelect) {
                    HJNewsTabModel *firstObjectModel = weakself.header.datas.firstObject;
                    [weakself selectTagModel:firstObjectModel];
                }
            }
        }
        [weakself.header reloadData];
        if (weakself.header.datas.count > weakself.header.selectIndexPath.row) {
            [weakself.header.collectionView scrollToItemAtIndexPath:weakself.header.selectIndexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:true];
        }
    }];
    
    [self presentViewController:informationTabController animated:NO completion:nil];
}

- (void)selectTagModel:(HJNewsTabModel *)tagModel {
    tagModel.isSelect = YES;
    dispatch_async_sql_queue(^{
        HJUserNewsTagModel *userTagModel = [HJUserNewsTagModel bg_find:[HJUserNewsTagModel bg_tableName] where:[NSString stringWithFormat:@"where %@=%@", bg_sqlKey(@"key"), bg_sqlValue([HJUserNewsTagModel getKeyWithUserId:HJUserInfo.userId typeId:toString(@(self.newsTypeId))])]].firstObject;
        userTagModel.selectTag = toString(@(tagModel.tagID));
        [userTagModel bg_saveOrUpdate];
    });
    
    self.selectTagId = toString(@(tagModel.tagID));
    [self loadNewNewsData];
}

- (NSArray *)getDatas {
    return self.datas;
}

- (void)loadNewNewsData {
    
    [HJInformationPresent loadNewsListWithType:self.type newsTypeId:self.newsTypeId tags:self.selectTagId pageIndex:1 complete:^(NSInteger serverPageSize, NSArray<HJInformationModel *> * _Nullable news, NSArray <HJFollowModel *>* _Nullable recommendUsers, NSError * _Nullable error) {
        
        [self.tableView.mj_header endRefreshing];
        self.pageIndex = 2;
        self.emptyDataHandler.canDisplay = YES;
        self.tableView.mj_header.hidden = NO;
        self.tableView.mj_footer.hidden = news.count == 0;
        [self hiddenLoading];
        
        if (!error) {
            if (news.count < serverPageSize) {
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }
            
            [self.datas removeAllObjects];
            
            for (HJInformationModel *model in news) {
                [self.datas addObject:[HJBlockchainInformationLayout layoutWithModel:model]];
            }
        }
        [self.tableView reloadData];
    }];
    
}

- (void)loadNewData {
    [self loadNewNewsData];
    [HJInformationPresent loadNewsTagsListWithTypeNewsTypeId:self.newsTypeId complete:^(NSArray * _Nullable datas) {
 
            if (!self.header.datas) {
                self.header.datas = [NSMutableArray array];
            } else {
                [self.header.datas removeAllObjects];
            }
            
            HJNewsTabModel *allModel = [HJNewsTabModel modelWithDict:@{
                @"tag_id": @-1,
                @"tag_name": @"ALL"
            }];
            [self.header.datas addObject:allModel];
            [self.header.datas addObjectsFromArray:datas.firstObject];
            
            BOOL isOldSelect = NO;
            for (HJNewsTabModel *model in self.header.datas) {
                if (model.tagID == [self.selectTagId integerValue]) {
                    model.isSelect = YES;
                    isOldSelect = YES;
                    break;
                }
            }
            
           NSLog(@"self.selectTagId = %@", self.selectTagId);

            if (!isOldSelect) {
                allModel.isSelect = YES;
            }
            
            NSLog(@"self.header.datas = %@", self.header.datas);
        [self.header reloadData];

    }];
}

- (void)loadMoreData {
    [HJInformationPresent loadNewsListWithType:self.type newsTypeId:self.newsTypeId tags:self.selectTagId pageIndex:self.pageIndex complete:^(NSInteger serverPageSize, NSArray<HJInformationModel *> * _Nullable news, NSArray <HJFollowModel *>* _Nullable recommendUsers, NSError * _Nullable error) {
        
        
        [self.tableView.mj_footer endRefreshing];
        
        if (error) {
            return;
        }
        
        self.pageIndex++;
        if (news.count < serverPageSize) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }
        
        if (news.count) {
            NSMutableArray *datas = [NSMutableArray array];
            for (HJInformationModel *model in news) {
                [datas addObject:[HJBlockchainInformationLayout layoutWithModel:model]];
            }
            [self.datas addObjectsFromArray:datas];
        }
        
        [self.tableView reloadData];
    }];
}


@end
